#! /bin/bash
# 接收1个参数：$1（all:重启所有，fe只重启前端，ng只重启nginx，be只重启后端）
# shell语法需注意：赋值语句的"="前后一定不要有空格，if语句的"="前后一定要有空格
result=""
cd ~/project/spring-study/
git pull
if [ $? -ne 0 ]; then
    result=$result"代码拉取失败... "
    echo $result
    exit -1
fi
if [ $1 ]; then
  if [ $1 != "fe" ] && [ $1 != "be" ] && [ $1 != "ng" ] && [ $1 != "all" ]; then
      echo "参数错误(fe,ng,be,all)"
      exit -1
  fi
  if [ $1 = "be" ] || [ $1 = "all" ]; then
    # 第一种写法
    processPid=`ps -ef | grep study-0.0.1-SNAPSHOT.jar | grep -v grep | awk '{print $2}' | head -1`
    # 第二种写法
    # processPid=`ps -ef | grep study-0.0.1-SNAPSHOT.jar | grep -v grep | awk 'NR==1 {print $2}'`
    # 即使进程id不存在的时候，processPid数据类型也是integer，这种情况默认赋值0以解决下面gt操作，不然会报错
    processPid=${processPid:=0}
    if [ $processPid -gt 0 ];then
      kill -9 $processPid
    else
       echo "java进程不存在，无需kill"
    fi
    /opt/maven/apache-maven-3.6.3/bin/mvn install -DskipTests
    if [ $? -ne 0 ]; then
        result=$result"mvn install失败... "
    else
      # springboot自带的tomcat和websocket冲突，需要跳过tests
      /opt/maven/apache-maven-3.6.3/bin/mvn package -DskipTests
      if [ $? -ne 0 ]; then
          result=$result"mvn package失败... "
      else
        cd target/
        nohup java -jar study-0.0.1-SNAPSHOT.jar &
        if [ $? -ne 0 ]; then
            result=$result"代码启动失败... "
        fi
      fi
    fi
  fi
  if [ $1 = "ng" ] || [ $1 = "all" ]; then
    cp -f ~/project/spring-study/nginx.conf /usr/local/nginx/conf/nginx.conf
    if [ $? -eq 0 ]; then
      /usr/local/nginx/sbin/nginx -s reload
      if [ $? -ne 0 ]; then
        result=$result"nginx.conf语法错误... "
      fi
    else
      result=$result"nginx.conf文件复制失败... "
    fi
  fi
  if [ $1 = "fe" ] || [ $1 = "all" ]; then
    cd ~/project/spring-study/nyn-vue
    npm install
    if [ $? -ne 0 ]; then
        result=$result"npm install失败... "
    else
      npm run build
      if [ $? -ne 0 ]; then
        result=$result"npm build失败... "
      fi
    fi
  fi
  if [ $result=="" ]; then
    echo "执行成功！"
  else
    echo $result
  fi
else
  echo "请输入参数(fe,ng,be,all)"
fi
